package com.aco.fatureapp.utilitary;

import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Spinner;

import com.aco.fatureapp.R;
import com.aco.fatureapp.auxiliary.MenuItem;

public class Utils {

	public static final int DIALOG_BLUETOOTH_NO_SUPPORT = 1001;

	public static String encryptMd5(final String s) {
		try {
			final byte[] mensagem = s.getBytes();

			final MessageDigest md = MessageDigest.getInstance("MD5");

			md.update(mensagem);

			final byte[] gerado = md.digest();

			final String retorno = Base64
					.encodeToString(gerado, Base64.DEFAULT);

			return retorno.trim();
		}
		catch (final Exception e) {
			return null;
		}

	}

	/**
	 *
	 * Responsável por verificar se o equipamento está conectado de alguma forma
	 * à internet.
	 *
	 * @param contexto
	 * @return
	 */
	public static boolean isInternetAvailable(final Context contexto) {
		try {
			final ConnectivityManager cm = (ConnectivityManager) contexto
					.getSystemService(Context.CONNECTIVITY_SERVICE);

			if (cm != null && cm.getActiveNetworkInfo() != null) {
				/* Conexão 3G */
				if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null
						&& cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
								.isAvailable()
						&& cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
								.isConnected()) {
					return true;
				}

				/* Conexão WIFI */
				else if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null
						&& cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
								.isAvailable()
						&& cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
								.isConnected()) {
					return true;
				}
			}

			/* Desconectado */
			return false;
		}
		catch (final Exception e) {
			return false;
		}
	}

	/**
	 * Método utilitário responsável por retornar o IMEI do aparelho.
	 *
	 * @param ctx
	 * @return
	 */
	public static String getImei(final Context ctx) {
		final TelephonyManager telephonyManager = (TelephonyManager) ctx
				.getSystemService(Context.TELEPHONY_SERVICE);

		return telephonyManager.getDeviceId();
	}

	/**
	 * Método facilitador para construção de um dialog com neutral button.
	 *
	 * @param ctx
	 * @param mens
	 * @param eventoOk
	 */
	public static void alert(final Context ctx, final String mens,
			final OnClickListener eventoOk) {
		new AlertDialog.Builder(ctx).setTitle("Atenção")
				.setIcon(R.drawable.ic_exclamacao).setMessage(mens)
				.setNeutralButton("OK", eventoOk).setCancelable(false).show();
	}

	/**
	 * Método facilitador para construção de um dialog com positive e negative
	 * buttons.
	 *
	 *
	 * @param ctx
	 * @param mens
	 * @param eventoSim
	 * @param eventoNao
	 * @param isPodeCancelar
	 */
	public static void alert(final Context ctx, final String mens,
			String labelSim, String labelNao, final OnClickListener eventoSim,
			final OnClickListener eventoNao, boolean isPodeCancelar) {
		Builder alert = new AlertDialog.Builder(ctx).setTitle("Confirmação")
				.setIcon(R.drawable.ic_interrogacao).setMessage(mens)
				.setPositiveButton(labelSim, eventoSim)
				.setNegativeButton(labelNao, eventoNao).setCancelable(false);

		if (isPodeCancelar) {
			alert.setCancelable(true);
		}
		alert.show();
	}

	public static void alert(final Context ctx, final String mens,
			final OnClickListener eventoSim, final OnClickListener eventoNao) {
		alert(ctx, mens, "Confirmar", "Cancelar", eventoSim, eventoNao, false);
	}

	/**
	 * Retorna a lista de itens do menu lateral.
	 *
	 * @return
	 */
	public static List<MenuItem> getLstMenuItem() {
		final List<MenuItem> itens = new ArrayList<MenuItem>();

		itens.add(new MenuItem("Início", R.drawable.ic_menu_lateral_inicio));

		itens.add(new MenuItem("Leitura", R.drawable.ic_menu_lateral_leitura));

		itens.add(new MenuItem("Carregar", R.drawable.ic_menu_lateral_carregar));

		itens.add(new MenuItem("Descarregar",
				R.drawable.ic_menu_lateral_descarregar));

		itens.add(new MenuItem("Encerrar Roteiro",
				R.drawable.ic_menu_lateral_encerrar_roteiro));

		itens.add(new MenuItem("Configurações",
				R.drawable.ic_menu_lateral_config));

		itens.add(new MenuItem("Impressora",
				R.drawable.ic_menu_lateral_impressora));

		itens.add(new MenuItem("Relatórios",
				R.drawable.ic_menu_lateral_relatorios));

		itens.add(new MenuItem("Sair", R.drawable.ic_menu_lateral_sair));

		return itens;
	}

	/**
	 * Buscar posição em um spinner para marcar a opção vinda do banco.
	 *
	 * @param spinner
	 * @param myString
	 * @return
	 */
	public static int getSpinnerIndex(final Spinner spinner,
			final String myString) {
		int index = 0;
		for (int i = 0; i < spinner.getCount(); i++) {
			if (spinner.getItemAtPosition(i).toString().equals(myString)) {
				index = i;
			}
		}
		return index;
	}

	public static BluetoothAdapter startBluetooth(final Activity context) {
		BluetoothAdapter bluetoothAdapter = BluetoothAdapter
				.getDefaultAdapter();

		if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			context.startActivityForResult(enableBtIntent,
					DIALOG_BLUETOOTH_NO_SUPPORT);
		}

		return bluetoothAdapter;
	}

	public static void hideTouch(Activity activity) {
		activity.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		InputMethodManager inputMethodManager = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
				.getWindowToken(), 0);
	}

	public static String formartZeroLeft(Number value, int qtdeZero) {
		if (value == null) {
			return " ";
		}

		return String.format("%0" + qtdeZero + "d", value);
	}

	public static String dateFormat(Long dateMilliseconds) {

		if (dateMilliseconds == null) {
			return "  /  /    ";
		}

		Calendar calendar = Calendar.getInstance(new Locale("pt", "BR"));
		calendar.setTimeInMillis(dateMilliseconds);

		DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM,
				new Locale("pt", "BR"));

		return dateFormat.format(calendar.getTime());
	}

	public static String formatValue(Double value) {
		if (value == null) {
			return " ";
		}

		DecimalFormat formatoDois = new DecimalFormat("##,###,###,##0.00",
				new DecimalFormatSymbols(new Locale("pt", "BR")));
		formatoDois.setMinimumFractionDigits(2);
		formatoDois.setParseBigDecimal(true);

		return formatoDois.format(value);
	}

	public static List<NameValuePair> getDefaultParams(String login,
			String senha, String imei) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		params.add(new BasicNameValuePair("imei", imei));
		params.add(new BasicNameValuePair("usuario", login));
		params.add(new BasicNameValuePair("senha", Utils.encryptMd5(senha)));

		return params;
	}

	public static void gravarSessao(final Context ctx, final String key,
			final String valor) {
		final SharedPreferences preference = PreferenceManager
				.getDefaultSharedPreferences(ctx);
		final SharedPreferences.Editor editor = preference.edit();
		editor.putString(key, valor);
		editor.commit();
	}

	public static void removerSessao(final Context ctx, final String key) {
		final SharedPreferences preference = PreferenceManager
				.getDefaultSharedPreferences(ctx);
		final SharedPreferences.Editor editor = preference.edit();
		editor.remove(key);
		editor.commit();
	}

	public static String recuperarSessao(final Context ctx, final String key) {
		if (ctx != null) {
			final SharedPreferences preference = PreferenceManager
					.getDefaultSharedPreferences(ctx);

			return preference.getString(key, "");
		}

		return null;
	}

}
